package com.gxa.goods.upload;

import com.gxa.goods.utils.TencentCOS;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Slf4j
@Api(value = "文件上传接口")
public class UploadController {


    @PostMapping("/cos")
    public String ossUpload(@RequestParam("file") MultipartFile file, String folder) throws IOException {

        //获取文件的名称
        String fileName = file.getOriginalFilename();

        //获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));

        //使用uuid作为文件名，防止生成的临时文件重复
        File tempFile = File.createTempFile("image-" + UUID.randomUUID().toString().replace("-",""), prefix);

        //将MultipartFile转换成File
        file.transferTo(tempFile);

        //上传文件到腾讯云存储
        //调用腾讯云工具上传文件
        String imageName = TencentCOS.uploadfile(tempFile, folder);

        //程序结束时，删除临时文件
        deleteFile(tempFile);

       log.debug("upload image url is {}",imageName);
//保存地址
        return "https://chenyang-1306361239.cos.ap-chengdu.myqcloud.com/"+imageName;
    }

    /**
     * 删除临时文件
     * @param files 临时文件，可变参数
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }





}
